package com.qf.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.pojo.TbCart;
import com.qf.pojo.TbUser;
import com.qf.service.CartService;
import com.qf.service.impl.CartServiceImpl;
import com.qf.utils.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/*
 *@Description:
 *@author:刘哥
 *@Date:86180 2022/8/17 11:29
 */
@WebServlet("/cart")
public class CartServlet extends  BaseServlet{
    private  CartService cartService=new CartServiceImpl();
    public  String show(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        TbUser user = (TbUser) request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }

        List<TbCart> cart = cartService.selectAll(user.getId());
        System.out.println("cart = " + cart);
        for (TbCart tbCart : cart) {
            System.out.println("tbCart.getGoodsList() = " + tbCart.getGoodsList());
        }
        request.getSession().setAttribute("cart",cart);
//        return "redirect:/demo.jsp";
        return "redirect:/cart.jsp";
    }
    public  String create(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        TbUser user = (TbUser) request.getSession().getAttribute("user");
        if (user == null) {
            return "/login.jsp";
        }
        String pid = request.getParameter("id");
        String number = request.getParameter("number");

        int num=1;
        if (!StringUtil.isEmpty(number)) {
            num= Integer.parseInt(number);
        }



        cartService.selectCart(user.getId(), Long.valueOf(pid),num);


        return "redirect:/cartSuccess.jsp";
    }
//    cart?method=delete&cid=1 删除
    public  String delete(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        TbUser user = (TbUser) request.getSession().getAttribute("user");
        if (user == null) {
            return "/login.jsp";
        }

        String pid = request.getParameter("cid");
        cartService.deleteCart(user.getId(),Long.parseLong(pid));
        return "redirect:/cart?method=show";
    }
//    cart?method=clear
    public  String clear(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        TbUser user = (TbUser) request.getSession().getAttribute("user");
        if (user == null) {
            return "/login.jsp";
        }

        cartService.clearCart(user.getId());
        return "redirect:/cart?method=show";
    }

}
